package com.heima.comment.service.impl;

import com.heima.comment.service.CommentRepayService;
import com.heima.common.exception.CustException;
import com.heima.feigns.UserFeign;
import com.heima.model.comment.dtos.CommentRepayLikeDTO;
import com.heima.model.comment.dtos.CommentRepaySaveDTO;
import com.heima.model.comment.pojos.ApComment;
import com.heima.model.comment.dtos.CommentRepayDTO;
import com.heima.model.comment.pojos.ApCommentRepay;
import com.heima.model.comment.pojos.ApCommentRepayLike;
import com.heima.model.comment.vo.ApCommentRepayVO;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.threadlocal.AppThreadLocalUtils;
import com.heima.model.user.pojos.ApUser;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.util.*;

@Slf4j
@Service
public class CommentRepayimpl implements CommentRepayService {

    @Autowired
    private UserFeign userFeign;

    @Autowired
    private MongoTemplate mongoTemplate;


    @Override
    public ResponseResult loadCommentRepay(CommentRepayDTO dto) {
        //校验参数
        //评论id不能为空  size为null 或 0 设置为10  最小日期为空 设置为当前
        if(dto.getSize()==null||dto.getSize()<=0){
            dto.setSize(10);
        }
        if(dto.getMinDate()==null){
            dto.setMinDate(new Date());
        }
        //条件查询评论回复信息
        //条件:  commentId = 评论id and createdTime 小于 minDate  创建时间 降序  limit size
        Query query = Query.query(Criteria.where("commentId").is(dto.getCommentId())
                .and("createdTime").lt(dto.getMinDate()));
        query.with(Sort.by(Sort.Order.desc("createdTime")));
        query.limit(dto.getSize());
        List<ApCommentRepay> list = mongoTemplate.find(query, ApCommentRepay.class);
        ApComment apComment = mongoTemplate.findById(dto.getCommentId(), ApComment.class);
        apComment.setReply(list.size());
        mongoTemplate.save(apComment);
        //检查是否登录
        // 如果未登录直接 返回评论回复列表
        ApUser user = AppThreadLocalUtils.getUser();
        if (user==null){
            return  ResponseResult.okResult(list);
        }
        //如果登录，需要判断哪些回复点过赞
        //基于当前列表 回复id集合  及  登录人id 查询回复点赞列表
        //遍历 当前回复列表，将每一个回复信息 封装成 vo
        // 判断当前回复id 在点赞信息中是否存在，如果存在 operation设置为0 不存在不做处理
        List<ApCommentRepayVO> vos = new ArrayList<>();
        for (ApCommentRepay apCommentRepay : list) {
            ApCommentRepayVO apCommentRepayVO = new ApCommentRepayVO();
            BeanUtils.copyProperties(apCommentRepay,apCommentRepayVO);
            Query query1 = Query.query(Criteria.where("authorId").is(user.getId())
                    .and("commentRepayId").is(apCommentRepay.getId())
                    .and("operation").is((short) 0));
            ApCommentRepayLike one = mongoTemplate.findOne(query1, ApCommentRepayLike.class);
            if(one!=null){
                apCommentRepayVO.setOperation((short)0);
            }
            vos.add(apCommentRepayVO);
        }
        return ResponseResult.okResult(vos);

    }

    @Override
    public ResponseResult saveCommentRepay(CommentRepaySaveDTO dto) {
        //校验参数
        //校验是否登录
        ApUser user = AppThreadLocalUtils.getUser();
        if (user == null) {
            CustException.cust(AppHttpCodeEnum.NEED_LOGIN);
        }
        //远程查询当前登陆用户信息
        ResponseResult<ApUser> userById = userFeign.findUserById(user.getId());
        //检查远程调用是否出现异常
        if (!userById.checkCode()) {
            //返回前端远程调用失败
            CustException.cust(AppHttpCodeEnum.REMOTE_SERVER_ERROR);
        }
        //获取用户信息
        ApUser apUser = userById.getData();

        //获取评论id
        String id = dto.getCommentId();
        //根据评论id查找是否存在
        Query query = Query.query(Criteria.where("_id").is(id));
        ApComment apComment = mongoTemplate.findOne(query, ApComment.class);
        if(apComment==null){
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"你回复的评论可能已删除");
        }
        ApCommentRepay apCommentRepay = new ApCommentRepay();
        //保存评论id
        apCommentRepay.setCommentId(apComment.getId());
        //保存用户id
        apCommentRepay.setAuthorId(user.getId());
        //保存回复内容
        apCommentRepay.setContent(dto.getContent());
        //获取用户名
        apCommentRepay.setAuthorName(apUser.getName());
        //保存创建时间
        apCommentRepay.setCreatedTime(new Date());
        //保存点赞数
        apCommentRepay.setLikes(0);
        //保存更新时间
        apCommentRepay.setUpdatedTime(new Date());
        mongoTemplate.save(apCommentRepay);
        return ResponseResult.okResult();
    }

    @Override
    public ResponseResult saveCommentRepayLike(CommentRepayLikeDTO dto) {
        // 校验登录  (必须登录)
        ApUser user = AppThreadLocalUtils.getUser();
        if(user==null){
            CustException.cust(AppHttpCodeEnum.NEED_LOGIN);
        }
        Map<Object, Object> map = new HashMap<>();
        //判断点赞信息是否存在
        ApCommentRepay byId = mongoTemplate.findById(dto.getCommentRepayId(), ApCommentRepay.class);
        if(byId==null){
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"回复信息不存在,可能已被删除");
        }
        if(dto.getOperation()==0){
            //根据用户id查询是否点过赞
            Query query = Query.query(Criteria.where("authorId").is(user.getId())
                    //回复id
                    .and("commentRepayId").is(byId.getId())
                    //点赞信息
                    .and("operation").is((short) 0));
            ApCommentRepayLike one = mongoTemplate.findOne(query, ApCommentRepayLike.class);
            if(one!=null){
                CustException.cust(AppHttpCodeEnum.DATA_NOT_ALLOW,"已经关注过了");
            }
            //未点过赞， 保存点赞信息
            ApCommentRepayLike apCommentRepayLike = new ApCommentRepayLike();
            apCommentRepayLike.setAuthorId(user.getId());
            apCommentRepayLike.setCommentRepayId(byId.getId());
            apCommentRepayLike.setOperation((short)0);
            mongoTemplate.save(apCommentRepayLike);
            //并将回复信息的点赞数量字段+1
            byId.setLikes(byId.getLikes()+1);
            mongoTemplate.save(byId);

            map.put("likes",byId.getLikes());
        }else {
            // 如果是取消赞
            //  删除点赞信息
            Query query = Query.query(Criteria.where("authorId").is(user.getId())
                    .and("commentRepayId").is(byId.getId())
                    .and("operation").is((short) 0));
            mongoTemplate.remove(query,ApCommentRepayLike.class);
            byId.setLikes(byId.getLikes()-1);
            if(byId.getLikes()<0){
                CustException.cust(AppHttpCodeEnum.DATA_NOT_ALLOW,"操作有误");
            }
            mongoTemplate.save(byId);

            //并将回复信息的点赞数量字段
            map.put("likes",byId.getLikes());
        }
        return ResponseResult.okResult(map);
    }
}
